package com.atguigu.gmall.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.utils.MyKafkaUtil;
import org.apache.flink.api.common.functions.RichFilterFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;

import java.text.SimpleDateFormat;

/**
 * Created on 2021/11/12.
 *
 * @author ${AUTHOR}
 */
public class UniqueVisitorApp {
    public static void main(String[] args) throws Exception {
        //TODO 1.基本环境准备
        //1.1 流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //1.2 设置并行度
        env.setParallelism(4);

        //TODO 2.检查点相关设置(略)
        //TODO 3.从Kafka中读取数据
        //3.1 声明消费的主题以及消费者组
        String topic ="dwd_page_log";
        String groupId = "unique_visitor_app_group";

        FlinkKafkaConsumer<String> kafkaSource = MyKafkaUtil.getKafkaSource(topic, groupId);
        DataStreamSource<String> kafkaDS = env.addSource(kafkaSource);

        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.map(JSON::parseObject);

        KeyedStream<JSONObject, String> keyedDS = jsonObjDS.keyBy(jsonObj -> jsonObj.getJSONObject("common").getString("mid"));


        SingleOutputStreamOperator<JSONObject> filter = keyedDS.filter(

                new RichFilterFunction<JSONObject>() {
                    private ValueState<String> lastVisitDateState;
                    private SimpleDateFormat sdf;

                    @Override
                    public void open(Configuration parameters) throws Exception {

                        ValueStateDescriptor<String> valueStateDescriptor = new ValueStateDescriptor<>("lastVisitDateState", String.class);

                        valueStateDescriptor.enableTimeToLive(StateTtlConfig.newBuilder(Time.days(1)).build());

                        lastVisitDateState = getRuntimeContext().getState(valueStateDescriptor);
                    }

                    @Override
                    public boolean filter(JSONObject jsonObj) throws Exception {
                        String lastPageId = jsonObj.getJSONObject("page").getString("last_page_id");

                        if (lastPageId != null && lastPageId.length() > 0) {
                            //如果last_page_id要是不为空   那么说明从其他页面跳过来的  ，直接将这条数据过滤
                            return false;
                        }
                        String lastVisitDate = lastVisitDateState.value();

                        Long ts = jsonObj.getLong("ts");
                        String curVisitDate = sdf.format(ts);

                        if (lastVisitDate != null && lastVisitDate.length() > 0 && curVisitDate.equals(lastVisitDate)) {
                            //已经访问过
                            return false;
                        } else {
                            //还没有访问过
                            lastVisitDateState.update(curVisitDate);
                            return true;
                        }
                    }
                }
        );
        filter
                .map( jsonObj->jsonObj.toJSONString())
                .addSink(MyKafkaUtil.getKafkaSink("dwm_unique_visitor" ));


        env.execute();

    }
}
